<template>
  <div class="app-container">

    <div id="divSearch" ref="divSearch">
      <el-form :inline="true" :model="Search" class="demo-form-inline">


        <el-form-item label="招聘类型" prop="Search">
          <el-select v-model="Search.BillType" placeholder="请选择" clearable>
            <el-option label="内部招聘" value=1></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
        <el-form-item label="名单类型" prop="Search">
          <el-select v-model="Search.blackType" placeholder="请选择" clearable>
            <el-option label="黑名单" value=1></el-option>
            <el-option label="白名单" value=2></el-option>
          </el-select>
        </el-form-item>

          <el-button type="primary" icon="el-icon-search" size="small" @click="getDataList">查询</el-button>
          <el-button type="success" icon="el-icon-circle-plus" size="small" @click="handeAdd">新增</el-button>

        </el-form-item>
      </el-form>
    </div>

    <el-table :data="queueList" style="width: 100%;" border>

      <el-table-column type="index" width="50" label="序号">
      </el-table-column>
      <el-table-column align="center" label="工号" width="80">
        <template slot-scope="scope">
          {{ scope.row.UserCode }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="姓名" width="80">
        <template slot-scope="scope">
          {{ scope.row.UserName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="身份证" width="165">
        <template slot-scope="scope">
          {{ scope.row.CardID }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="招聘类型" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.BillType===1">内部招聘</span>
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="名单类型"  width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.blackType===1">黑名单</span>
          <span v-if="scope.row.blackType===2">白名单</span>
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="单位">
        <template slot-scope="scope">
          {{ scope.row.OrganizeName }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="header-center" label="离职时间">
        <template slot-scope="scope">
          {{ scope.row.LeaveDate }}
        </template>
      </el-table-column> -->
      <el-table-column align="header-center" label="职位" width="180">
        <template slot-scope="scope">
          {{ scope.row.JobName }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="职级" width="80">
        <template slot-scope="scope">
          {{ scope.row.JobLevel }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope)">修改</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
          background
          layout="sizes, prev, pager, next,total"
          :page-size="Search.pageSize"
          :total="Search.total"
          @current-change="pageChange"
        /> -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'创建'" width="50%" top="20px">
      <el-form :model="EditObj" label-width="120px" label-position="left">
        <el-form-item label="工号">
          <el-input v-model="EditObj.UserCode" placeholder=" 工号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="EditObj.UserName" placeholder=" 姓名" />
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="EditObj.CardID" placeholder=" 身份证" />
        </el-form-item>
        <el-form-item label="招聘类型">
          <el-input v-model="EditObj.BillType" placeholder="" />
        </el-form-item>
        <el-form-item label="名单类型">
          <el-input v-model="EditObj.blackType" placeholder="" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="primary" @click="confirmData">提交</el-button>
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible2" :title="dialogType==='edit'?'编辑':'导入'" width="90%" top="20px">

      <el-button size="mini" type="success" icon="el-icon-s-order" @click="savePeopleDetail" style="float: left;">保存</el-button>
      <el-button type="success" @click="addRow(1)" icon="el-icon-download"  style="float: left;" size="mini" >添加一行</el-button>
      <el-button type="success" @click="download" icon="el-icon-download" style="float: left;" size="mini" >下载模板</el-button>
      <el-upload class="upload-demo" action :on-change="handleChange" :on-remove="handleRemove" :on-exceed="handleExceed"
        :limit="1" :show-file-list="false" accept="application/vnd.openxmlformats-
            officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        :auto-upload="false">
        <el-button :loading="importLoading" size="mini" type="success" icon="el-icon-upload2" style="float: left; margin-left: 5px;">上传数据</el-button>

      </el-upload>

      <el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)" :data="formPeopleDetail" style="width: 100%;margin-top: 0px;"
        border>
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column align="center" label="工号">
          <template slot-scope="scope">
            <el-input v-model="scope.row.UserCode"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="姓名">
          <template slot-scope="scope">
            <el-input v-model="scope.row.UserName"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="身份证">
          <template slot-scope="scope">
            <el-input v-model="scope.row.CardID"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="招聘类型">
          <template slot-scope="scope">
            <el-input v-model="scope.row.BillType"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名单类型">
          <template slot-scope="scope">
            <el-input v-model="scope.row.blackType"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle size="small" @click="delPeople(scope)"></el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-dialog>
  </div>
</template>

<script>
  import path from 'path'
  import {
    deepClone
  } from '@/utils'
  import {
    getBlackList,
    updateBlackList,
    deleteBlackList
  } from '@/api/getSelect'
  import { downloadFile } from "@/api/upload";
  // 默认的编辑字段
  const defaultObject = {

  }


  export default {
    name: "QueueList",

    data() {
      return {
        EditObj: Object.assign({}, defaultObject),
        queueList: [], //队列的列表 在el-table中用
        formPeopleDetail: [],
        dialogVisible: false,
        importLoading: false,
        dialogVisible2: false,
        Search: { // 查询条件
          total: 0, // 总记录数
          pageSize: 10, // 一页显示的记录数
          page: 1, // /当前页码
          RNO: '004', // 表编号  根据Controller中对应的表编号
          jsWhere: '' // 自定义条件
        }
      }
    },
    computed: {
      routesData() {
        return this.routes
      }
    },
    created() {
      // Mock: get all routes and roles list from server

      this.getDataList()
    },
    methods: {
      pageChange(page) { // 翻页
        this.Search.page = page

        this.getDataList()
      },
      async getDataList() { // 获取列表数据，通用
        let where = "";
        if(this.Search.BillType!= null&&this.Search.BillType!= ""){
          where  = where + " and BillType ="+this.Search.BillType
        }
       if(this.Search.blackType!=null&&this.Search.blackType!=""){
          where  = where + " and blackType ="+this.Search.blackType
        }
        console.log(where)
        const res = await getBlackList({
          jswhere: where
        })
        this.queueList = res.data.Table
      },
      sortChange: function(column) {
        // column, prop, order,排序，通用
        
        this.Search.sort = column.prop + ' ' + column.order

        this.getDataList()
      },
      handeAdd() { // 新建
        this.formPeopleDetail =[]
        this.dialogVisible2 = true
      },

      handleEdit(scope) { // 修改
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.checkStrictly = true
        this.EditObj = deepClone(scope.row)
        this.$nextTick(() => {
          const routes = this.generateRoutes(this.EditObj.routes)
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))
          // set checked state of a node not affects its father and child nodes
          this.checkStrictly = false
        })

      },
      async handleDelete({
        $index,
        row
      }) {
        this.$confirm('确定删除该记录吗?', '警告', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(async () => {
            await deleteBlackList({
              ID: JSON.stringify(row.ID)
            })
            this.queueList.splice($index, 1)
            if (result.code === 20000) {
              this.dialogVisible = false
              this.$notify({
                title: 'Success',
                dangerouslyUseHTMLString: true,
                message: result.message,
                type: 'success'
              })
            } else {
              this.$notify({
                title: 'error',
                dangerouslyUseHTMLString: true,
                message: result.message,
                type: 'error'
              })
            }

          })

      },
      delPeople({
        $index,
        row
      }) {
        if (row.ID != undefined) {
          this.$confirm('确定删除序号为 ' + row.ID + ' 的数据吗?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            await deleteBody({
              ID: JSON.stringify(row.ID)
            })
            this.formPeopleDetail.splice($index, 1)
          })

        } else {
          this.formPeopleDetail.splice($index, 1);
        }
      },
      //导入后保存
      async savePeopleDetail() {
        const resultP = await updateBlackList({
          PeopleDate: JSON.stringify(this.formPeopleDetail),
          IsPostBack: true,
        });
        if (resultP.code === 20000) {
          this.dialogVisible2 = false
          this.getDataList()
          this.$notify({
            title: 'Success',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'success'
          })
        } else {
          this.$notify({
            title: 'error',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'error'
          })
        }
        this.getDataList()
      },
      async confirmData() { // 提交数据，需要修改
        this.formPeopleDetail[0] = this.EditObj
        const resultP = await updateBlackList({
          PeopleDate: JSON.stringify(this.formPeopleDetail),
          billID: this.EditObj.ID,
          IsPostBack: true,
        });
        if (resultP.code === 20000) {
          this.dialogVisible = false
          this.getDataList()
          this.$notify({
            title: 'Success',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'success'
          })
        } else {
          this.$notify({
            title: 'error',
            dangerouslyUseHTMLString: true,
            message: result.message,
            type: 'error'
          })
        }
        this.getDataList()
      },
      //增加行
      addRow(types) {
        let list = {};
        if (types == 1) {
          this.formPeopleDetail.push(list);
        }
      },
      //上传文件时处理方法
      handleChange(file, fileList) {

        this.importLoading = true;
        this.fileTemp = file.raw;
        if (this.fileTemp) {
          if (
            this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            this.fileTemp.type == "application/vnd.ms-excel"
          ) {
            this.importfxx(this.fileTemp);
          } else {
            this.$message({
              type: "warning",
              message: "附件格式错误，请删除后重新上传！",
            });
            this.importLoading = false;
          }
        } else {
          this.$message({
            type: "warning",
            message: "请上传附件！",
          });
          this.importLoading = false;
        }
      },
      //超出最大上传文件数量时的处理方法
      handleExceed() {
        this.$message({
          type: "warning",
          message: "超出最大上传文件数量的限制！",
        });
        return;
      },
      //上传对数据处理
      importfxx(obj) {

        let _this = this;
        let inputDOM = this.$refs.inputer;
        // 通过DOM取文件数据

        this.file = event.currentTarget.files[0];

        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;

        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
          var binary = "";
          var rABS = false; //是否将文件读取为二进制字符串
          var pt = this;
          var wb; //读取完成的数据
          var outdata;
          var reader = new FileReader();
          reader.onload = function(e) {
            var bytes = new Uint8Array(reader.result);
            var length = bytes.byteLength;
            for (var i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i]);
            }
            //此处引入，用于解析excel
            var XLSX = require("xlsx");
            if (rABS) {
              wb = XLSX.read(btoa(fixdata(binary)), {
                //手动转化
                type: "base64",
              });
            } else {
              wb = XLSX.read(binary, {
                type: "binary",
              });
            }
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
            //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
            //此处可对数据进行处理
            let arr = [];
            outdata.map((v) => {
              let obj = {};
              obj.UserCode = v["工号"];
              obj.UserName = v["姓名"];
              obj.CardID = v["身份证"];
              obj.BillType = v["招聘类型"];
              obj.blackType = v["名单类型"];
              arr.push(obj);
            });
            //alert(this.form.PersonnelloanNo)
            /* alert("111")
            alert(_this.$route.query.JumpID) */
            for (let i = 0; i < arr.length; i++) {
              if(arr[i].BillType == "内部招聘"){
                arr[i].BillType = 1
              }
              //arr[i].PersonnelloanNo = _this.tentPersonnelloanNo;
              _this.formPeopleDetail.push(arr[i]);
            }
            _this.importLoading = false;
            return arr;
          };
          reader.readAsArrayBuffer(f);
        };
        if (rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      },
      //下载模板
      async download() {
        const url = await downloadFile({
          fileName: "黑白名单导入格式.xlsx",
          path:
            "UploadFiles\\" +
            "Common\\" +
            "DownloadFile\\" +
            "黑白名单导入格式.xlsx",
        });

        let blob = new Blob([url], {
          type: "application/vnd.ms-excel",
        });
        let requestUrl = URL.createObjectURL(blob);
        let link = document.createElement("a");
        let fileName = "模板" + ".xlsx";
        document.body.appendChild(link);
        link.href = requestUrl;
        link.dowmload = fileName;
        link.click();
        link.remove();
      },

    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    .EditObjs-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 5px;
    }
  }
</style>
